package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDTO;
import com.itheima.dto.SetmealDTO;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/*套餐*/
@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;

    /**
     * <p>Description: 添加套餐</p>
     *
     * @author liuyiming
     * @date 2022-10-12 12:20
     * @version 1.0.0
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> addSetmeal(@RequestBody SetmealDTO setmealDto){
        log.info("添加套餐");
        setmealService.addSetmeal(setmealDto);
        return R.success("添加成功");
    }

    /**
     * <p>Description: 分页查询套餐</p>
     *
     * @author liuyiming
     * @date 2022-10-12 16:16
     * @version 1.0.0
     */
    @GetMapping("/page")
    @Cacheable(value = "setmealCache")
    public R<Page> page(int page,int pageSize,String name){
        log.info("分页查询套餐");
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(StringUtils.isNotBlank(name),Setmeal::getName,name);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,lambdaQueryWrapper);
        if (pageInfo.getRecords().size() == 0){
            return R.success(pageInfo);
        }

        //把套餐中的分类ID存入一个Set中（因为Set能去重），然后查询分类信息
        Set<Long> categoryIdsBySet = pageInfo.getRecords().stream().map(item -> item.getCategoryId()).collect(Collectors.toSet());
        List<Category> categories = categoryService.listByIds(categoryIdsBySet);

        //创建一个Map集合，存储分类Id和分类Name
        Map<Long, String> collect = categories.stream().collect(Collectors.toMap(Category::getId, Category::getName));
        //循环遍历 给分类的名称赋值
        for (Setmeal setmeal : pageInfo.getRecords()) {
            //获取方法是：通过套餐中的分类id取出对应的值，并赋值给套餐实体类中的categoryName
            setmeal.setCategoryName(collect.get(setmeal.getCategoryId()));
        }
        return R.success(pageInfo);
    }
    
    /**
     * <p>Description: 删除套餐</p>
     * 
     * @author liuyiming
     * @date 2022-10-12 17:30
     * @version 1.0.0
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        log.info("删除套餐{}",ids);
        setmealService.deleteWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * <p>Description: 批量停售/起售套餐</p>
     *
     * @author liuyiming
     * @date 2022-10-12 20:56
     * @version 1.0.0
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> updateStatus(@PathVariable Integer status, Long[] ids){
        LambdaQueryWrapper<Setmeal>  setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        setmealService.update(setmeal, setmealLambdaQueryWrapper);
        return R.success("状态修改成功");
    }

    /**
     * <p>Description: 根据条件查询菜品信息</p>
     *
     * @author liuyiming
     * @date 2022-10-13 14:52
     * @version 1.0.0
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache")
    public R<List<Setmeal>> list(Setmeal setmeal){
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        setmealLambdaQueryWrapper.orderByAsc(Setmeal::getUpdateTime);
        setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
        List<Setmeal> list = setmealService.list(setmealLambdaQueryWrapper);
        return R.success(list);
    }
    
    /**
     * <p>Description: 根据ID查询套餐具体信息</p>
     * 
     * @author liuyiming
     * @date 2022-10-14 10:07
     * @version 1.0.0
     */
    @GetMapping("/{setmealId}")
    @Cacheable(value = "setmealCache")
    public R<SetmealDTO> querySetmealInfoById(@PathVariable Long setmealId){
        log.info("根据ID查询套餐具体信息");
        SetmealDTO setmealDto = setmealService.querySetmealInfoById(setmealId);
        return R.success(setmealDto);
    }

    /**
     * <p>Description: 根据ID修改套餐具体内容</p>
     *
     * @author liuyiming
     * @date 2022-10-14 14:39
     * @version 1.0.0
     */
    @PutMapping
    @CacheEvict(value = "setmealCache", allEntries = true)
    public R<String> updateSetmealInfoById(@RequestBody SetmealDTO setmealDTO){
        log.info("根据ID修改套餐具体内容");
        setmealService.updateSetmealInfoById(setmealDTO);
        return R.success("修改成功");
    }
    
    /**
     * <p>Description: 查询套餐中的菜品信息</p>
     * 
     * @author liuyiming
     * @date 2022-10-13 22:06
     * @version 1.0.0
     */
    @GetMapping("/dish/{setmealId}")
    @Transactional
    @Cacheable(value = "setmealCache")
    public R<List<DishDTO>> getDishInfo(@PathVariable Long setmealId){
        log.info("通过套餐ID查询菜品数据");
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmealId);
        List<SetmealDish> setmealDishLists = setmealDishService.list(setmealDishLambdaQueryWrapper);
        List<DishDTO> dishes = new ArrayList<>();
        for (SetmealDish setmealDish : setmealDishLists) {
            DishDTO dishDTO = new DishDTO();
            Dish dishInfo = dishService.getById(setmealDish.getDishId());
            BeanUtils.copyProperties(dishInfo,dishDTO);
            dishDTO.setCopies(setmealDish.getCopies());
            dishes.add(dishDTO);
        }
        return R.success(dishes);
    }
    
    
    



}
